'use client'

import { useState, useRef, ChangeEvent, useCallback } from 'react'
import { Button } from '@/components/ui/button'
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import { toast } from 'sonner'
import { Loader2, Upload, X } from 'lucide-react'
import { useAvatarUpload } from '@/api/uploads'

interface AvatarUploadProps {
  value?: string
  onChange: (url: string) => void
  className?: string
}

export function AvatarUpload({ value, onChange, className = '' }: AvatarUploadProps) {
  const [isUploading, setIsUploading] = useState(false)
  const [previewUrl, setPreviewUrl] = useState<string | null>(value || null)
  const fileInputRef = useRef<HTMLInputElement>(null)

  // 上传进度
  const [uploadProgress, setUploadProgress] = useState(0)

  // 使用头像上传钩子
  const avatarUpload = useAvatarUpload()

  // 处理文件选择
  const handleFileChange = async (e: ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (!file) return

    // 验证文件类型
    if (!file.type.startsWith('image/')) {
      toast.error('请选择图片文件')
      return
    }

    // 验证文件大小 (最大2MB)
    if (file.size > 2 * 1024 * 1024) {
      toast.error('图片大小不能超过2MB')
      return
    }

    // 创建本地预览
    const localPreviewUrl = URL.createObjectURL(file)
    setPreviewUrl(localPreviewUrl)

    // 上传文件
    setIsUploading(true)
    setUploadProgress(0)

    try {
      const response = await avatarUpload.mutateAsync({
        file,
        onProgress: (percent) => {
          setUploadProgress(percent)
        }
      })
      // 获取返回的文件URL
      const fileUrl = response.data.data.url
      onChange(fileUrl ?? '')
      toast.success('头像上传成功')
    } catch (_error) {
      // 上传失败处理
      // 错误已在 useAvatarUpload 中处理，这里只需恢复原头像
      setPreviewUrl(value || null)
    } finally {
      setIsUploading(false)
      setUploadProgress(0)
      // 释放本地预览URL
      URL.revokeObjectURL(localPreviewUrl)
    }
  }

  // 使用useCallback缓存回调函数，避免不必要的重新渲染
  const triggerFileSelect = useCallback(() => {
    fileInputRef.current?.click()
  }, [])

  // 使用useCallback缓存回调函数，避免不必要的重新渲染
  const clearAvatar = useCallback(() => {
    setPreviewUrl(null)
    onChange('')
  }, [onChange])

  // 获取用户名首字母作为头像占位符
  const getInitials = () => {
    return 'U'
  }

  return (
    <div className={`flex flex-col items-center gap-2 ${className}`}>
      <div className="relative">
        <Avatar className="h-24 w-24 cursor-pointer" onClick={triggerFileSelect}>
          <AvatarImage src={previewUrl || ''} alt="头像" />
          <AvatarFallback className="bg-primary text-primary-foreground text-xl">
            {getInitials()}
          </AvatarFallback>
        </Avatar>

        {isUploading && (
          <div className="absolute inset-0 flex flex-col items-center justify-center bg-background/80 rounded-full">
            <Loader2 className="h-8 w-8 animate-spin text-primary" />
            {uploadProgress > 0 && (
              <div className="mt-1 text-xs font-medium text-primary">{uploadProgress}%</div>
            )}
          </div>
        )}

        {previewUrl && !isUploading && (
          <button
            type="button"
            onClick={clearAvatar}
            className="absolute -top-2 -right-2 rounded-full bg-destructive p-1 text-destructive-foreground hover:bg-destructive/90"
          >
            <X className="h-4 w-4" />
          </button>
        )}
      </div>

      <input
        type="file"
        ref={fileInputRef}
        onChange={handleFileChange}
        accept="image/*"
        className="hidden"
      />

      <Button
        type="button"
        variant="outline"
        size="sm"
        onClick={triggerFileSelect}
        disabled={isUploading}
        className="flex items-center gap-1"
      >
        <Upload className="h-4 w-4 mr-1" />
        {previewUrl ? '更换头像' : '上传头像'}
      </Button>
    </div>
  )
}